package com.bbzn.device.client.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author wulongbo
 * @Date 2021/9/28 11:05
 * @Version 1.0
 */
public class MsgTemplateUtil {

    public static <K, V> String replacePlaceHolderWithMapValue(String msg, Map<K, V> placeHolderMap) {
        /**
         * \w  单词字符：[a-zA-Z_0-9]
         *
         * ([\\w]+)表示对匹配的内容中进行捕获，捕获值存入matcher.group中
         */

        Pattern pattern = Pattern.compile("\\$*!?\\{([\\w]+)\\}");
        Matcher matcher = pattern.matcher(msg);
        Map<String, String> replaceList = new HashMap();
        while (matcher.find()) {
            String placeHolder = matcher.group(0);
            String key = matcher.group(1);
            Object value = placeHolderMap.get(key);
            if (value != null) {
                replaceList.put(placeHolder, value.toString());
            }
        }
        for (Map.Entry<String, String> keyValue : replaceList.entrySet()) {
            msg = msg.replace(keyValue.getKey(), keyValue.getValue());
        }
        return msg;
    }
}
